package ru.xeden.web.html.builder;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import ru.xeden.web.html.component.IComponentFactory;
import ru.xeden.web.html.dom.INode;

public class SaxNodeBuilder
    implements INodeBuilder
    
{
    private InputStream inputStream;
    
    public SaxNodeBuilder(InputStream inputStream)
        throws DocumentBuilderException
    {
        if (inputStream == null)
        {
            throw new DocumentBuilderException(DocumentBuilderException.IDS_XML_INPUT_SOURCE_MUST_BE_NOT_NULL);
        }
        
        if(inputStream instanceof BufferedInputStream)
        {
            this.inputStream = inputStream;
        }
        else
        {
            this.inputStream = new BufferedInputStream(inputStream);
        }
        
    }
    
    public INode build(IComponentFactory componentFactory)
        throws DocumentBuilderException
    {
        SaxHandler handler = new SaxHandler(componentFactory);
        try
        {
            XMLReader reader = XMLReaderFactory.createXMLReader();
            reader.setContentHandler(handler);
            reader.setEntityResolver(handler);
            reader.parse(new InputSource(inputStream));
        }
        catch (SAXException e)
        {
            throw new DocumentBuilderException(e);
        }
        catch (IOException e)
        {
            throw new DocumentBuilderException(e);
        }
        finally
        {
            try
            {
                inputStream.close();
            }
            catch (IOException e)
            {
                throw new DocumentBuilderException(e);
            } 
        }
        
        return handler.getElement();
    }
}
